<?php

namespace maotool\util;

use maotool\file\FileUtil;
use maotool\object\StrUtil;

class IniFileUtil
{

    public static function parse($path = "project:/.env")
    {
        $path = PathUtil::path($path);
        $content = FileUtil::read($path);
        $lines = preg_split('/\r\n|\r|\n/', $content);
        $config = array();
        $section = null;

        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || strpos($line, ';') === 0 || strpos($line, '#') === 0 || strpos($line, '//') === 0) {
                continue;
            }

            if (preg_match('/^\[(.*?)]$/', $line, $matches)) {
                // 匹配 section
                $section = $matches[1];
                if (StrUtil::hasNotEmpty($section)) {
                    $config[$section] = array();
                } else {
                    $section = null;
                }
            } elseif (strpos($line, '=') !== false) {
                $parts = explode('=', $line, 2);
                $key = trim($parts[0]);
                $value = isset($parts[1]) ? trim($parts[1]) : '';
                // 去除值中的双引号或单引号
                if ((substr($value, 0, 1) === '"' && substr($value, -1) === '"') ||
                    (substr($value, 0, 1) === "'" && substr($value, -1) === "'")) {
                    $value = substr($value, 1, -1);
                } elseif (strtolower($value) === 'true') {
                    $value = true;
                } elseif (strtolower($value) === 'false') {
                    $value = false;
                } elseif (is_numeric($value)) {
                    $value = $value + 0;
                } elseif (strpos($value, ',') !== false) {
                    $value = array_map('trim', explode(',', $value));
                }
                if ($section !== null) {
                    $config[$section][$key] = $value;
                } else {
                    $config[$key] = $value;
                }
            }
        }

        return $config;
    }

}